package com.turman.coroutionsample.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.turman.coroutionsample.db.AppDatabase
import com.turman.coroutionsample.db.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

class UserViewModel(app: Application) : AndroidViewModel(app) {
//    private val _userList = MutableLiveData<List<User>>()
//    val userList:LiveData<List<User>> = _userList

    fun insert(uid: String, firstName: String, lastName: String) {
        viewModelScope.launch {
            AppDatabase.getInstance(getApplication()).userDao()
                .insert(User(uid.toInt(), firstName, lastName))
        }
    }

    fun getAll(): Flow<List<User>> {
        return AppDatabase.getInstance(getApplication()).userDao().queryAll()
            .catch { e -> e.printStackTrace() }.flowOn(Dispatchers.IO)
    }

//    fun getAll2() {
//        viewModelScope.launch {
//            _userList.postValue(AppDatabase.getInstance(getApplication()).userDao().queryAll2())
//        }
//    }
}